const { Article, User } = require("../model");

// 获取文章列表
exports.getAriticles = async (req, res, next) => {
  try {
    const { limit = 20, offset = 0, tag, author } = req.query;
    //筛选标签
    const filter = {};
    if (tag) {
      filter.tagList = tag;
    }
    //筛选作者
    if (author) {
      const user = await User.findOne({ username: author });
      filter.author = user ? user._id : null;
    }

    const articles = await Article.find(filter)
      .skip(Number.parseInt(offset)) //跳过n条
      .limit(Number.parseInt(limit)) //取n条
      .sort({
        createdAt: -1, //-1倒序，1正序
      });
    const articlesCount = await Article.countDocuments();
    return res.status(200).json({
      articles,
      articlesCount,
    });
  } catch (error) {
    next(error);
  }
};
// 获取用户关注的作者文章列表
exports.getFeedArticles = async (req, res, next) => {
  try {
    res.send("get user");
  } catch (error) {
    next(error);
  }
};
// 获取文章
exports.getAriticle = async (req, res, next) => {
  try {
    const article = await Article.findById(req.params.articleId).populate(
      "author"
    );
    if (!article) {
      return res.status(404).end();
    }
    res.status(200).json({
      article,
    });
  } catch (error) {
    next(error);
  }
};
// 创建文章
exports.createAriticle = async (req, res, next) => {
  try {
    const article = new Article(req.body.article);
    article.author = req.user._id;
    // 根据id映射user数据
    article.populate("author").execPopulate();
    await article.save();
    return res.status(201).json({
      article,
    });
  } catch (error) {
    next(error);
  }
};
// 更新文章
exports.updateArticle = async (req, res, next) => {
  try {
    const article = req.article;
    const bodyArticle = req.body.article;
    article.title = bodyArticle.title || article.title;
    article.description = bodyArticle.description || article.description;
    article.body = bodyArticle.body || article.body;
    await article.save();
    res.status(200).json({
      article,
    });
  } catch (error) {
    next(error);
  }
};
// 删除文章
exports.deleteAriticle = async (req, res, next) => {
  try {
    const article = req.article;
    await article.remove();
    res.status(204).end("删除成功");
  } catch (error) {
    next(error);
  }
};
// 添加文章评论
exports.addComments = async (req, res, next) => {
  try {
    res.send("get user");
  } catch (error) {
    next(error);
  }
};
// 获取文章评论
exports.getComments = async (req, res, next) => {
  try {
    res.send("get user");
  } catch (error) {
    next(error);
  }
};
// 删除文章评论
exports.deleteComments = async (req, res, next) => {
  try {
    res.send("get user");
  } catch (error) {
    next(error);
  }
};
// 标记喜欢的文章
exports.favoriteArticles = async (req, res, next) => {
  try {
    res.send("get user");
  } catch (error) {
    next(error);
  }
};
// 标记不喜欢的文章
exports.unfavoriteArticles = async (req, res, next) => {
  try {
    res.send("get user");
  } catch (error) {
    next(error);
  }
};
